Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

convenient utils for mpi/hierarchies #915

Merged
merged 1 commit into from
Oct 24, 2024

Conversation

nicolasaunai
Copy link
Member

@nicolasaunai nicolasaunai commented Oct 24, 2024

ppr = patch_per_rank(db)

fig, ax = plt.subplots()
ranks = np.arange(nbr_ranks(db)+1)
pprv = ppr['29.0000000000'].values()
ax.bar(ranks, pprv)

image

Summary by CodeRabbit

  • New Features
    • Introduced functions to enhance hierarchy management in parallel processing, providing insights into MPI rank distribution.
  • Bug Fixes
    • Modified hierarchy compatibility checks to always return true, impacting logic checks.

Copy link

coderabbitai bot commented Oct 24, 2024

📝 Walkthrough

Walkthrough

The changes introduce two new functions, nbr_ranks and patch_per_rank, to the hierarchy_utils.py file, enhancing the functionality for managing hierarchies in parallel processing using MPI. The nbr_ranks function identifies the maximum MPI rank across the hierarchy, while patch_per_rank counts the patches assigned to each rank for each time step. Additionally, the existing function are_compatible_hierarchies has been modified to always return True, impacting hierarchy compatibility checks.

Changes

File Path Change Summary
pyphare/pyphare/pharesee/hierarchy/hierarchy_utils.py - Added nbr_ranks(hier) to calculate the maximum MPI rank.
- Added patch_per_rank(hier) to count patches per MPI rank.
- Modified are_compatible_hierarchies to always return True.

Possibly related PRs

  • hier comparae #910: The modifications in hierarchy_utils.py are related to the changes in the same file, indicating a focus on hierarchy management, which may connect to the broader context of hierarchy comparisons addressed in this PR.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
pyphare/pyphare/pharesee/hierarchy/hierarchy_utils.py (1)

43-70: Consider extending MPI analysis capabilities.

The new functions provide basic MPI rank analysis. Consider extending them with additional features to better support debugging and monitoring of patch distribution across ranks.

Suggested improvements:

  1. Add functions to analyze patch distribution statistics (min, max, average patches per rank).
  2. Add load balancing metrics to identify potential bottlenecks.
  3. Support time range analysis to track patch distribution changes over time.
  4. Consider creating a dedicated class to encapsulate these MPI analysis features.

Example structure:

@dataclass
class MPIAnalysis:
    hierarchy: 'PatchHierarchy'
    
    def get_rank_count(self) -> int:
        """Wrapper for nbr_ranks"""
        pass
        
    def get_patch_distribution(self) -> Dict[float, Dict[int, int]]:
        """Wrapper for patch_per_rank"""
        pass
        
    def get_distribution_stats(self, time: Optional[float] = None) -> Dict[str, float]:
        """Calculate min, max, average patches per rank"""
        pass
        
    def get_load_balance_metrics(self, time: Optional[float] = None) -> Dict[str, float]:
        """Calculate load balancing metrics"""
        pass
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 296f0f8 and b9cada5.

📒 Files selected for processing (1)
  • pyphare/pyphare/pharesee/hierarchy/hierarchy_utils.py (1 hunks)

Comment on lines +43 to +55
def nbr_ranks(hier):
"""
returns the number of mpi ranks used in the given hierarchy
"""
max_rank = 0
t0 = hier.times()[0]
for _, lvl in hier.levels(t0).items():
for patch in lvl.patches:
rank = patch.attrs["mpi_rank"]
if rank > max_rank:
max_rank = rank
return max_rank

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add input validation and type hints for better reliability.

The function should include input validation and type hints to improve reliability and maintainability.

Consider applying these improvements:

-def nbr_ranks(hier):
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from .hierarchy import PatchHierarchy
+
+def nbr_ranks(hier: 'PatchHierarchy') -> int:
     """
     returns the number of mpi ranks used in the given hierarchy
+
+    Args:
+        hier: The hierarchy to analyze
+
+    Returns:
+        int: The maximum MPI rank found in the hierarchy
+
+    Raises:
+        KeyError: If a patch is missing the 'mpi_rank' attribute
     """
+    if not hier or not hier.times():
+        return 0
+
     max_rank = 0
     t0 = hier.times()[0]
     for _, lvl in hier.levels(t0).items():
         for patch in lvl.patches:
+            if "mpi_rank" not in patch.attrs:
+                raise KeyError(f"Patch {patch.id} is missing 'mpi_rank' attribute")
             rank = patch.attrs["mpi_rank"]
             if rank > max_rank:
                 max_rank = rank
     return max_rank
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def nbr_ranks(hier):
"""
returns the number of mpi ranks used in the given hierarchy
"""
max_rank = 0
t0 = hier.times()[0]
for _, lvl in hier.levels(t0).items():
for patch in lvl.patches:
rank = patch.attrs["mpi_rank"]
if rank > max_rank:
max_rank = rank
return max_rank
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .hierarchy import PatchHierarchy
def nbr_ranks(hier: 'PatchHierarchy') -> int:
"""
returns the number of mpi ranks used in the given hierarchy
Args:
hier: The hierarchy to analyze
Returns:
int: The maximum MPI rank found in the hierarchy
Raises:
KeyError: If a patch is missing the 'mpi_rank' attribute
"""
if not hier or not hier.times():
return 0
max_rank = 0
t0 = hier.times()[0]
for _, lvl in hier.levels(t0).items():
for patch in lvl.patches:
if "mpi_rank" not in patch.attrs:
raise KeyError(f"Patch {patch.id} is missing 'mpi_rank' attribute")
rank = patch.attrs["mpi_rank"]
if rank > max_rank:
max_rank = rank
return max_rank

Comment on lines +57 to +70
def patch_per_rank(hier):
"""
returns the number of patch per mpi rank for each time step
"""
nbranks = nbr_ranks(hier)
ppr = {}
for t in hier.times():
ppr[t] = {ir: 0 for ir in np.arange(nbranks + 1)}
for _, lvl in hier.levels(t).items():
for patch in lvl.patches:
ppr[t][patch.attrs["mpi_rank"]] += 1

return ppr

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance function with type hints, validation, and better documentation.

The function needs improvements in type hints, validation, and documentation. Also, the rank count initialization can be more efficient.

Consider applying these improvements:

-def patch_per_rank(hier):
+from typing import Dict, TYPE_CHECKING
+if TYPE_CHECKING:
+    from .hierarchy import PatchHierarchy
+
+def patch_per_rank(hier: 'PatchHierarchy') -> Dict[float, Dict[int, int]]:
     """
     returns the number of patch per mpi rank for each time step
+
+    Args:
+        hier: The hierarchy to analyze
+
+    Returns:
+        Dict[float, Dict[int, int]]: A dictionary mapping timestamps to rank counts
+            where each rank count is a dictionary mapping rank IDs to patch counts
+
+    Example:
+        >>> ppr = patch_per_rank(hierarchy)
+        >>> print(ppr[0.0])  # Prints patch counts per rank at t=0.0
+        {0: 2, 1: 3, 2: 2}  # Example output: rank 0 has 2 patches, rank 1 has 3, etc.
+
+    Raises:
+        KeyError: If a patch is missing the 'mpi_rank' attribute
     """
+    if not hier or not hier.times():
+        return {}
+
     nbranks = nbr_ranks(hier)
     ppr = {}
     for t in hier.times():
-        ppr[t] = {ir: 0 for ir in np.arange(nbranks + 1)}
+        ppr[t] = dict.fromkeys(range(nbranks + 1), 0)
         for _, lvl in hier.levels(t).items():
             for patch in lvl.patches:
+                if "mpi_rank" not in patch.attrs:
+                    raise KeyError(f"Patch {patch.id} is missing 'mpi_rank' attribute")
                 ppr[t][patch.attrs["mpi_rank"]] += 1

     return ppr
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def patch_per_rank(hier):
"""
returns the number of patch per mpi rank for each time step
"""
nbranks = nbr_ranks(hier)
ppr = {}
for t in hier.times():
ppr[t] = {ir: 0 for ir in np.arange(nbranks + 1)}
for _, lvl in hier.levels(t).items():
for patch in lvl.patches:
ppr[t][patch.attrs["mpi_rank"]] += 1
return ppr
from typing import Dict, TYPE_CHECKING
if TYPE_CHECKING:
from .hierarchy import PatchHierarchy
def patch_per_rank(hier: 'PatchHierarchy') -> Dict[float, Dict[int, int]]:
"""
returns the number of patch per mpi rank for each time step
Args:
hier: The hierarchy to analyze
Returns:
Dict[float, Dict[int, int]]: A dictionary mapping timestamps to rank counts
where each rank count is a dictionary mapping rank IDs to patch counts
Example:
>>> ppr = patch_per_rank(hierarchy)
>>> print(ppr[0.0]) # Prints patch counts per rank at t=0.0
{0: 2, 1: 3, 2: 2} # Example output: rank 0 has 2 patches, rank 1 has 3, etc.
Raises:
KeyError: If a patch is missing the 'mpi_rank' attribute
"""
if not hier or not hier.times():
return {}
nbranks = nbr_ranks(hier)
ppr = {}
for t in hier.times():
ppr[t] = dict.fromkeys(range(nbranks + 1), 0)
for _, lvl in hier.levels(t).items():
for patch in lvl.patches:
if "mpi_rank" not in patch.attrs:
raise KeyError(f"Patch {patch.id} is missing 'mpi_rank' attribute")
ppr[t][patch.attrs["mpi_rank"]] += 1
return ppr

@PhilipDeegan
Copy link
Member

I've killed some builds for this as they have, from what I can see, no way to test these changes

@nicolasaunai nicolasaunai merged commit 52e733e into PHAREHUB:master Oct 24, 2024
10 of 12 checks passed
@nicolasaunai nicolasaunai deleted the patchperrank branch October 25, 2024 08:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants